import baseRequest from './request'
import JSDom from 'jsdom'
import Jquery from 'jquery'
import request from "request";

const {JSDOM} = JSDom

interface GetSessionConfig {
    username: string,
    password: string
}

// 将html转为JSDom并用jquery来操作
export const translateJSDOM = (webPage: string) => {
    const {window} = new JSDOM(webPage)

    return Jquery(window)
}

// 切割字符串
const cutString = (stringValue:string, cutValue:string):string => {
    let index = stringValue.indexOf(cutValue);
    return stringValue.substring(0, index);
}

// 获取session
export const getSession = (config:GetSessionConfig) =>{
    return new Promise(async (resolve, reject) =>{
        const data = {
            "USERNAME": config.username,
            "PASSWORD": config.password
        }
        const res:any = await new Promise((resolve,reject)=>{
            request.post({
                url: 'http://jwmis.wuyiu.edu.cn/jsxsd/xk/LoginToXk',
                form: data
            },(error:any, response,body:any)=>{
                resolve(response)
            })
        })
        // console.log(res)
        const session:string = cutString(res.headers['set-cookie'][0],';')
        resolve(session)
    })
}
